<template>
	<div class="app-container">
		<el-row :gutter="20">
			<!--分组数据-->
			<el-col :span="4" :xs="24">
				<div>
					<el-button type="primary" size="mini" @click="handleQueryAll"
						>全部展示</el-button
					>
				</div>
				<div class="head-container" style="margin-top:5px">
					<el-input
						v-model="name"
						:placeholder="$t('equipment.groupingInput')"
						clearable
						size="small"
						prefix-icon="el-icon-search"
						style="margin-bottom: 20px"
					/>
				</div>
				<div class="head-container tree">
					<el-tree
						ref="tree"
						:data="groupOptions"
						:props="defaultProps"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						:highlight-current="true"
						default-expand-all
						@node-click="handleNodeClick"
					>
						<div
							slot-scope="{ node, data }"
							class="el-tree-node__label custom-tree-node custom-tree-item"
							style="position: relative;"
						>
							<span class="name">{{ data.name }}</span>
							<div
								class="right-btns"
								style="position: absolute;right: 0; top: 0; background: #F5F7FA; height: 100%"
								@click.stop
							>
								<svg-icon
									v-hasPerm="['group_add']"
									icon-class="plus"
									@click="addGroup(node, data)"
								/>
								<svg-icon
									v-hasPerm="['group_edit']"
									icon-class="edit"
									@click="editGroup(node, data)"
								/>
								<svg-icon
									v-if="data.parentId > 0"
									v-hasPerm="['group_del']"
									icon-class="delete"
									@click="deleteGroup(node, data)"
								/>
							</div>
						</div>
					</el-tree>
				</div>
			</el-col>

			<!--素材数据-->
			<el-col :span="20" :xs="24">
				<el-form
					v-show="showSearch"
					ref="queryForm"
					:model="queryParams"
					:inline="true"
					label-width="68px"
				>
					<el-form-item :label="$t('material.materialName')" prop="name">
						<el-input
							v-model="queryParams.name"
							:placeholder="$t('material.materialNameInput')"
							clearable
							size="small"
							@keyup.enter.native="handleQuery"
						/>
					</el-form-item>
					<el-form-item :label="$t('program.status')" prop="status">
						<el-select
							v-model="queryParams.status"
							:placeholder="$t('equipment.statusSelect')"
							clearable
							size="small"
						>
							<el-option
								v-for="dict in statusOptions"
								:key="dict.value"
								:label="dict.label"
								:value="dict.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('elButton.establishTime')">
						<el-date-picker
							v-model="dateRange"
							size="small"
							style="width: 240px"
							value-format="yyyy-MM-dd"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('elButton.startTime')"
							:end-placeholder="$t('elButton.endTime')"
						/>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							icon="el-icon-search"
							size="mini"
							@click="handleQuery"
							>{{ $t('elButton.search') }}
						</el-button>
						<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
							$t('elButton.reset')
						}}</el-button>
					</el-form-item>
				</el-form>

				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['material_add']"
							type="primary"
							icon="el-icon-plus"
							size="mini"
							@click="handleAdd"
							>{{ $t('elButton.add') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['material_edit']"
							type="success"
							icon="el-icon-edit"
							size="mini"
							:disabled="single"
							@click="handleEdit"
							>{{ $t('elButton.change') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['material_del']"
							type="danger"
							icon="el-icon-delete"
							size="mini"
							:disabled="multiple"
							@click="handleDel"
							>{{ $t('elButton.delete') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							v-hasPerm="['material_move']"
							type="success"
							icon="el-icon-position"
							size="mini"
							:disabled="multiple"
							@click="handleMoveTo"
							>{{ $t('elButton.move') }}
						</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-radio-group
							v-model="type"
							class="custom-group"
							size="mini"
							@change="handleTypeChange"
						>
							<el-radio border :label="$t('material.all')" />
							<el-radio border :label="$t('material.pictures')" />
							<el-radio border :label="$t('material.video')" />
							<el-radio border :label="$t('material.file')" />
							<el-radio border :label="$t('material.audio')" />
							<el-radio border :label="$t('material.other')" />
						</el-radio-group>
					</el-col>
					<div class="top-right-btn">
						<el-tooltip
							class="item"
							effect="dark"
							:content="$t('elButton.refresh')"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-refresh"
								@click="handleQuery"
							/>
						</el-tooltip>
						<el-tooltip
							class="item"
							effect="dark"
							:content="
								showSearch
									? $t('elButton.hideSearch')
									: $t('elButton.showSearch')
							"
							placement="top"
						>
							<el-button
								size="mini"
								circle
								icon="el-icon-search"
								@click="showSearch = !showSearch"
							/>
						</el-tooltip>
					</div>
				</el-row>

				<el-table
					v-loading="loading"
					:data="materialList"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="50" align="center" />
					<el-table-column
						:label="$t('equipment.number')"
						align="center"
						width="50"
						prop="id"
					/>
					<el-table-column
						:label="$t('material.materialName')"
						align="center"
						prop="name"
						:show-overflow-tooltip="true"
					>
						<template slot-scope="scope">
							<span
								style="cursor:pointer"
								@click="
									nameUpdate(scope.row.id, scope.row.name, scope.row.groupId)
								"
								>{{ scope.row.name }}</span
							>
							<!-- <span v-hasPerm="['material_edit']" style="cursor:pointer" @click="nameUpdate(scope.row.id,scope.row.name,scope.row.groupId)">{{ scope.row.name }}</span> -->
						</template>
					</el-table-column>
					<el-table-column
						:label="$t('equipment.sort')"
						align="center"
						prop="groupName"
					/>
					<el-table-column
						:label="$t('equipment.resolving')"
						align="center"
						prop="resolution"
					/>
					<el-table-column
						:label="$t('material.format')"
						align="center"
						width="50"
						prop="format"
					/>
					<el-table-column
						:label="$t('material.size')"
						align="center"
						prop="fileSize"
					>
					</el-table-column>
					<el-table-column
						:label="$t('material.timeOrPage')"
						align="center"
						width="80"
						prop="duration"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.type == 'file'"
								>{{ scope.row.duration }}{{ $t('material.page') }}</span
							>
							<span v-else
								>{{ scope.row.duration }}{{ $t('material.second') }}</span
							>
						</template>
					</el-table-column>
					<!-- <el-table-column
						:label="$t('program.status')"
						align="center"
						prop="status"
						:formatter="statusFormat"
					/> -->
					<el-table-column
						:label="$t('elButton.establishTime')"
						align="center"
						prop="createTime"
						width="180"
					>
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.createTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column
						:label="$t('equipment.control')"
						align="center"
						class-name="small-padding fixed-width"
						width="200px"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="scope.row.type !== 'file'"
								size="mini"
								type="text"
								icon="el-icon-view"
								@click="handlePreview(scope.row)"
								>{{ $t('elButton.preview') }}
							</el-button>
							<el-button
								v-if="scope.row.status == '1' || scope.row.status == '3'"
								v-hasPerm="['material_audit']"
								size="mini"
								type="text"
								icon="el-icon-circle-check"
								@click="handleAudit(scope.row)"
								>{{ $t('elButton.examine') }}
							</el-button>
							<el-button
								v-hasPerm="['material_audit']"
								size="mini"
								type="text"
								icon="el-icon-tickets"
								@click="auditRecord(scope.row)"
								>{{ $t('elButton.examineRecord') }}
							</el-button>
							<el-button
								v-hasPerm="['bizinfo_export']"
								type="text"
								icon="el-icon-download"
								size="mini"
								@click="handleExport(scope.row)"
								>下载
							</el-button>
							<el-button
								v-hasPerm="['upload_again']"
								size="mini"
								type="text"
								icon="el-icon-circle-check"
								@click="uploadAgain(scope.row)"
								>{{ $t('elButton.resetUpload') }}
							</el-button>
							<!-- <el-button
                v-hasPerm="['material_edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >修改
              </el-button> -->
							<el-button
								v-hasPerm="['material_del']"
								size="mini"
								type="text"
								icon="el-icon-delete"
								@click="handleDel(scope.row)"
								>{{ $t('elButton.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination
					v-show="total > 0"
					:total="total"
					:page.sync="queryParams.current"
					:limit.sync="queryParams.size"
					@pagination="getList"
				/>
			</el-col>
		</el-row>

		<!-- 审核记录 -->
		<el-dialog
			:title="title"
			:visible.sync="auditRecordOpen"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
		>
			<el-table v-loading="loading" :data="auditRecordList" max-height="70vh">
				<el-table-column
					:label="$t('program.reviewer')"
					align="center"
					prop="checkBy"
				/>
				<el-table-column
					:label="$t('program.auditStatus')"
					align="center"
					prop="status"
				>
					<template slot-scope="scope">
						<span v-if="scope.row.status === 2">{{
							$t('program.auditStatus1')
						}}</span>
						<span v-if="scope.row.status === 3">{{
							$t('program.auditStatus2')
						}}</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('equipment.remarks')"
					align="center"
					prop="remarks"
				/>
				<el-table-column
					:label="$t('wel.info.time')"
					align="center"
					prop="checkTime"
					width="180"
				>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.checkTime) }}</span>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<!-- 添加或修改素材对话框 -->
		<el-dialog
			:title="$t('material.uploadMaterial')"
			:visible.sync="open"
			:close-on-click-modal="false"
			:modal-append-to-body="true"
			:append-to-body="true"
			width="40%"
			class="custom-dialog"
			@close="reset"
		>
			<el-form ref="form" :model="form" label-width="80px">
				<el-row>
					<el-form-item
						:label="$t('material.materialSort')"
						prop="groupId"
						:rules="[
							{ required: true, message: $t('material.uploadMaterialRule') },
						]"
					>
						<treeselect
							v-model="form.groupId"
							:options="groupOptions.length ? groupOptions[0].children : []"
							:normalizer="normalizer"
							:placeholder="$t('material.materialSortInput')"
						/>
					</el-form-item>
					<el-form-item v-if="open" :label="$t('material.chooseSort')">
						<el-upload
							ref="upload"
							class="upload-demo"
							drag
							multiple
							:headers="{
								Authorization: 'Bearer ' + getAccessToken(),
							}"
							:limit="30"
							:action="`${VUE_APP_BASE_API}/ips/material/upload`"
							:on-success="handleOnSuccess"
							:on-error="handleOnError"
							:before-upload="uploadBefore"
						>
							<i class="el-icon-upload" />
							<div class="el-upload__text">
								{{ $t('edition.uploadDrop')
								}}<em>{{ $t('edition.uploadClick') }}</em>
							</div>
							<div
								v-if="form.url"
								slot="tip"
								class="el-upload__tip"
								style="font-size:16px"
							>
								{{ form.name }}
								<span v-if="successTitle" style="color:#67C23A;font-size:20px"
									>【{{ successTitle }}】</span
								>
							</div>
							<div
								v-else-if="successTitle"
								slot="tip"
								class="el-upload__tip"
								style="font-size:16px"
							>
								<span style="color:#67C23A;font-size:20px"
									>【{{ successTitle }}】</span
								>
							</div>
						</el-upload>
					</el-form-item>
					<el-form-item label="自动转换" v-if="isVideoMaterial">
						<el-switch
							v-model="form.isConvert"
							active-color="#13ce66"
							inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
						>
						</el-switch>
					</el-form-item>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button
					:disabled="!form.url"
					type="primary"
					:loading="saveLoading"
					@click="submitForm"
					>{{ $t('submitText') }}
				</el-button>
				<el-button @click="open = false">{{ $t('cancelText') }}</el-button>
			</span>
		</el-dialog>

		<!-- 添加或修改素材对话框 -->
		<el-dialog
			:title="$t('material.changeMaterialName')"
			:visible.sync="nameUpdateOpen"
			:close-on-click-modal="false"
			:modal-append-to-body="true"
			:append-to-body="true"
			width="30%"
			class="custom-dialog"
			@close="reset"
		>
			<el-form ref="form" :model="form" label-width="100px">
				<el-row>
					<el-form-item
						:label="$t('material.materialName')"
						prop="name"
						:rules="[
							{ required: true, message: $t('material.materialNameRule') },
						]"
					>
						<el-input
							v-model="form.name"
							:placeholder="$t('material.materialNameInput')"
							clearable
							size="small"
						/>
					</el-form-item>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button
					type="primary"
					:loading="saveLoading"
					@click="nameUpdateSure"
					>{{ $t('submitText') }}</el-button
				>
				<el-button @click="nameUpdateOpen = false">{{
					$t('cancelText')
				}}</el-button>
			</span>
		</el-dialog>

		<!-- 添加或修改素材对话框 -->
		<el-dialog
			:title="$t('material.resetUpload')"
			:visible.sync="uploadAgainOpen"
			:close-on-click-modal="false"
			:modal-append-to-body="true"
			:append-to-body="true"
			width="40%"
			class="custom-dialog"
			@close="reset"
		>
			<el-form ref="form" :model="form" label-width="100px">
				<el-row>
					<el-form-item :label="$t('material.chooseSort')">
						<el-upload
							ref="upload"
							class="upload-demo"
							drag
							multiple
							:headers="{
								Authorization: 'Bearer ' + getAccessToken(),
							}"
							:limit="30"
							:action="`${VUE_APP_BASE_API}/ips/material/upload`"
							:on-success="handleOnSuccess"
							:on-error="handleOnError"
							:before-upload="uploadBefore"
						>
							<i class="el-icon-upload" />
							<div class="el-upload__text">
								{{ $t('edition.uploadDrop')
								}}<em>{{ $t('edition.uploadClick') }}</em>
							</div>
							<div
								v-if="form.url"
								slot="tip"
								class="el-upload__tip"
								style="font-size:16px"
							>
								{{ form.name }}
								<span v-if="successTitle" style="color:#67C23A;font-size:20px"
									>【{{ successTitle }}】</span
								>
							</div>
							<div
								v-else-if="successTitle"
								slot="tip"
								class="el-upload__tip"
								style="font-size:16px"
							>
								<span style="color:#67C23A;font-size:20px"
									>【{{ successTitle }}】</span
								>
							</div>
						</el-upload>
					</el-form-item>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button
					:disabled="!form.url"
					type="primary"
					:loading="saveLoading"
					@click="submitForm"
					>{{ $t('submitText') }}
				</el-button>
				<el-button @click="uploadAgainOpen = false">{{
					$t('cancelText')
				}}</el-button>
			</span></el-dialog
		>

		<!--添加/编辑分组-->
		<el-dialog
			:visible.sync="groupDialogVisible"
			:modal-append-to-body="true"
			:close-on-click-modal="false"
			:append-to-body="true"
			:title="$t('material.sort')"
			width="30%"
			class="wrapper"
			@closed="groupDialogClosed"
		>
			<el-form
				ref="form"
				@submit.native.prevent
				:model="groupObj"
				:rules="groupRules"
				label-width="80px"
			>
				<el-form-item :label="$t('equipment.sort')" prop="name">
					<el-input
						ref="name"
						v-model="groupObj.name"
						size="small"
						@keyup.enter.native="handleClickSaveGroup"
					/>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleClickSaveGroup">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="groupDialogVisible = false">{{
					$t('cancelText')
				}}</el-button>
			</span>
		</el-dialog>

		<!--审核页面-->
		<audit
			:obj="auditObj"
			:visible.sync="auditVisible"
			audit-title="素材审核"
			audit-type="material"
			@refresh="getList"
		>
			<div v-if="auditObj">
				<div v-if="showImg(auditObj)" class="img-wrapper">
					<el-image :src="VUE_APP_BASE_API + auditObj.originalUrl">
						<div slot="error" class="image-slot">{{ auditObj.name }}</div>
					</el-image>
				</div>
				<!-- <div v-if="showPdf(auditObj) && numPages" class="pdf-wrapper">
          <pdf
            v-for="i in numPages"
            :key="i"
            :src="src"
            :page="i"
          />
        </div> -->
				<div v-if="showVideo(auditObj)" class="video-wrapper">
					<video
						:src="VUE_APP_BASE_API + auditObj.originalUrl"
						style="width: 100%"
					/>
				</div>
			</div>
		</audit>

		<!-- 移至对话框 -->
		<el-dialog
			:title="$t('program.moveSort')"
			:visible.sync="mtOpen"
			width="560px"
			center
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
		>
			<el-form label-width="85px">
				<el-row>
					<el-col :span="24">
						<el-form-item :label="$t('equipment.sort')" prop="groupId">
							<treeselect
								v-model="groupId"
								:options="groupOptions.length ? groupOptions[0].children : []"
								:normalizer="normalizer"
								:placeholder="$t('material.materialSortInput')"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click="mtCancel">{{
					$t('cancelText')
				}}</el-button>
				<el-button size="small" type="primary" @click="mtSubmitForm">{{
					$t('submitText')
				}}</el-button>
			</div>
		</el-dialog>

		<!-- 预览素材 -->
		<el-dialog
			:title="$t('elButton.preview')"
			:visible.sync="previewVisible"
			:modal-append-to-body="true"
			:append-to-body="true"
			:close-on-click-modal="false"
			width="50%"
			@closed="handleClosed"
		>
			<div v-if="previewVisible">
				<img
					v-if="previewObj.type === 'image'"
					:src="
						`${VUE_APP_BASE_API}${previewObj.decodedUrl ||
							previewObj.decodedUrl}`
					"
					alt=""
					style="width: 100%"
				/>
				<video
					v-if="previewObj.type === 'media'"
					autoplay
					controls
					:src="
						`http://${staticPort}${previewObj.decodedUrl ||
							previewObj.decodedUrl}`
					"
					style="width: 100%"
				/>
				<!-- <pdf
          v-if="previewObj.type === 'file'"
          :src="src"
          :page="1"
        /> -->
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="previewVisible = false">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="previewVisible = false">{{
					$t('cancelText')
				}}</el-button>
			</span>
		</el-dialog>
		<!-- 删除素材警告 -->
		<el-dialog
			title="警告"
			:visible.sync="deleteProgramDialog"
			width="30%"
			:before-close="handleClose"
			append-to-body="true"
		>
			<span>删除失败,该素材已应用于下列节目：</span>
			<div class="dialog-info">
				<div v-for="item in deleteProgramInfo">
					<p>节目编码：{{ item.id }}/节目名称：{{ item.name }}</p>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="deleteProgramDialog = false"
					>确认</el-button
				>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import {
	listMaterial,
	getMaterial,
	delMaterial,
	addMaterial,
	editMaterial,
	moveTo,
} from '@/api/ips/material'
import {
	groupTree,
	delGroup,
	addGroup,
	editGroup,
	whetherMaterial,
} from '@/api/ips/group'
import { listauditRecord } from '@/api/ips/audit'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getAccessToken } from '@/data/user'
import AuditMixin from '@/mixins/audit/index.js'
import { getLabelByValInTree } from '@/utils/obj-util'
import eventbus from '@/utils/eventbus'
import Store from '@/store/index'
// import pdf from '@/components/Pdf/index.vue'
// import pdf from 'vue-pdf'

export default {
	name: 'Material',
	components: {
		Treeselect,
		// pdf
	},
	mixins: [AuditMixin],
	data() {
		const nameValidator = (rule, val, callback) => {
			if (val) {
				callback()
			} else {
				callback(new Error(this.$t('equipment.groupingInput')))
			}
		}
		return {
			currentPage: 0, // pdf文件页码
			pageCount: 0, // pdf文件总页数
			pageNum: 1,
			pageTotalNum: 1, // 总页数
			loadedRatio: 0, // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
			VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,
			getAccessToken,
			successTitle: '',
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 总条数
			total: 0,
			// 素材表格数据
			materialList: [],
			// 弹出层标题
			title: '',
			// 是否显示上传dialog
			open: false,
			mtOpen: false,
			groupId: undefined,
			groupName: undefined,
			// 日期范围
			dateRange: [],
			// 状态字典
			statusOptions: [], // 查询参数
			name: undefined,
			type: '全部',
			groupOptions: [],
			defaultProps: {
				children: 'children',
				label: 'name',
			},
			queryParams: {
				current: 1,
				size: 10,
				fullPathId: 20,
				name: undefined,
				groupName: undefined,
				status: undefined,
				createTime: undefined,
				type: undefined,
			},
			// 显示搜索条件
			showSearch: true,
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				name: [
					{
						required: true,
						message: this.$t('material.templateNameEmpty'),
						trigger: 'change',
					},
				],
			},
			// 上传文件的list
			fileList: [],
			saveLoading: false,
			// 分组相关
			groupDialogVisible: false,
			groupObj: { name: undefined },
			groupRules: {
				name: [{ validator: nameValidator }],
			},
			// 这两个是给vue-pdf用的
			numPages: null,
			src: null,
			// 审核记录
			auditRecordOpen: false,
			auditRecordList: [],
			// 预览相关
			previewObj: null,
			previewVisible: false,
			nameUpdateOpen: false,
			uploadAgainOpen: false,
			// 删除素材弹框
			deleteProgramDialog: false,
			deleteProgramInfo: [],
			// 是否是音频类素材
			isVideoMaterial: false,
			formList: [],
			staticPort: '',
		}
	},
	watch: {
		// 根据名称筛选分组名称树
		name(val) {
			this.$refs.tree.filter(val)
		},
		auditVisible(val) {
			if (val) {
				// 打开了审核dialog
				if (this.showPdf(this.auditObj)) {
					// 如果是pdf，那么要加载pdf
					window.pdfjsLib
						.getDocument(
							process.env.VUE_APP_BASE_API + this.auditObj.decodedUrl
						)
						.then((src) => {
							this.src = src
							this.numPages = src.numPages
						})
				}
			} else {
				// 关闭了审核dialog
				if (this.numPages !== null) {
					this.numPages = null
					this.src = null
				}
			}
		},
		previewVisible(val) {
			console.log('val', val)
			if (val) {
				console.log(this.previewObj)
				if (this.previewObj.type === 'file') {
					// 如果是pdf，那么要加载pdf
					window.pdfjsLib
						.getDocument(
							process.env.VUE_APP_BASE_API + this.previewObj.decodedUrl
						)
						.then((src) => {
							this.src = src
							console.log('this.src', src)
							console.log('this.numPages', src.numPages)
							this.numPages = src.numPages
						})
				}
			}
		},
	},
	mounted() {
		eventbus.$on('websocket', (data) => {
			if (data.type == '112') {
				this.getList()
			}
		})
		eventbus.$on('websocket', (data) => {
			if (data.type == '120' /*后端定义常量消息结构：给web发送弹窗消息*/) {
				var msg = data.payload.msg
				console.log(msg)
			}
		})
		eventbus.$on('deteleProgram', (data) => {
			this.deleteProgramDialog = true
			this.deleteProgramInfo = data
		})
		this.$once('hook:beforeDestroy', () => {
			eventbus.$off('websocket')
			eventbus.$off('deteleProgram')
		})
	},
	created() {
		this.getList()
		this.getGroupTree()
		this.getDicts('material_status').then((response) => {
			this.statusOptions = response.data
		})
		// 获取后端ip
		this.staticPort = Store.state.user.staticPort
	},
	methods: {
		test() {
			this.$message({
				type: 'error',
				message: '测试一下',
				showClose: true,
			})
		},
		handleClosed() {
			this.previewObj = null
		},
		uploadBefore(file) {
			console.log('uploadBeforeuploadBeforeuploadBeforeuploadBefore', file)
			if (file.type.includes('video') || file.type.includes('audio')) {
				this.isVideoMaterial = true
			} else {
				this.isVideoMaterial = false
			}
			this.successTitle = '上传中'
		},
		// 上传成功
		handleOnSuccess(res) {
			console.log('res', res)
			if (res.code === '1') {
				this.$message({ type: 'error', message: res.msg, showClose: true })
			} else {
				this.loading = false
				this.successTitle = '上传成功'
				this.form.realFileName = res.realFileName
				this.form.fileSize = res.fileSize
				this.form.type = res.fileType
				this.form.format = res.fileFormat
				this.form.name = res.fileName
				this.form.url = res.path
				const _form = Object.assign({}, this.form)
				// 存储已成功的this.form用于多次save
				this.formList.push(_form)
				// this.open = false
				// this.uploadAgainOpen = false
				// this.saveLoading = false
				// this.$message({
				//   message: this.$t('uploadSuccess'),
				//   type: 'success',
				//   showClose: true
				// })
			}
		},
		// 上传失败
		handleOnError() {
			this.$message({
				message: this.$t('edition.uploadFail'),
				type: 'error',
				showClose: true,
			})
		},

		getNameById(arr, id) {
			for (let i = 0; i < arr.length; i++) {
				if (arr[i].id === id) {
					return arr[i].name
				}
			}
			return ''
		},
		handleClickSave() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					// 拿到分组名字
					// this.form.groupName = this.getNameById(this.groupOptions, this.form.groupId)
					this.form.groupName = getLabelByValInTree(
						this.groupOptions,
						this.form.groupId,
						{
							label: 'name',
							value: 'id',
						}
					)
					const intervalId = setInterval(() => {
						if (this.form.groupId && this.form.groupName) {
							clearInterval(intervalId)
							this.$refs.upload.submit()
							this.loading = this.$loading({
								lock: true,
								text: this.$t('uploading'),
								spinner: 'el-icon-loading',
								background: 'hsla(0,0%,100%,.9)',
							})
						}
						// if (!this.uploadUrl().endsWith('=undefined')) {

						// }
					}, 500)
				}
			})
		},
		// 上传的url
		uploadUrl() {
			let mateId = -1
			if (this.form.id) {
				mateId = this.form.id
			}
			return `${this.VUE_APP_BASE_API}/ips/material/upload?groupId=${
				this.form.groupId
			}&groupName=${this.form.groupName}&mateId=${mateId}`
		},
		handleTypeChange(val) {
			switch (val) {
				case '全部':
					this.queryParams.type = undefined
					break
				case '图片':
					this.queryParams.type = 'image'
					break
				case '视频':
					this.queryParams.type = 'media'
					break
				case '音频':
					this.queryParams.type = 'audio'
					break
				case '文档':
					this.queryParams.type = 'file'
					break
				default:
					this.queryParams.type = 'other'
					break
			}
			this.getList()
		},
		/** 查询素材列表 */
		getList() {
			this.loading = true
			listMaterial(this.addDateRange(this.queryParams, this.dateRange)).then(
				(response) => {
					this.materialList = response.data
					this.total = response.total
					this.loading = false
				}
			)
		},
		/** 转换机构数据结构 */
		normalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children
			}
			return {
				id: node.id,
				label: node.name,
				children: node.children,
			}
		},
		/** 查询分组名称下拉树结构 */
		getGroupTree() {
			groupTree({ groupId: 20 }).then((response) => {
				this.groupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.groupOptions, this.groupDict)
			})
		},
		// 筛选节点
		filterNode(value, data) {
			if (!value) return true
			return data.name.indexOf(value) !== -1
		},
		// 节点单击事件
		handleNodeClick(data) {
			this.queryParams.fullPathId = data.id
			// this.queryParams.current = 1
			this.getList()
		},
		// 状态字典翻译
		statusFormat(row, column) {
			return this.selectDictLabel(this.statusOptions, row.status)
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				name: undefined,
				groupId: undefined,
				groupName: undefined,
				resolution: undefined,
				format: undefined,
				size: undefined,
				duration: undefined,
				originalUrl: undefined,
				decodedUrl: undefined,
				deptId: undefined,
				deptName: undefined,
				status: undefined,
			}
			this.successTitle = ''
			this.resetForm('form')
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1
			this.getList()
		},
		handleQueryAll() {
			this.queryParams.fullPathId = ''
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.dateRange = []
			this.resetForm('queryForm')
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = this.$t('material.addMaterial')
		},
		/** 预览按钮操作 */
		handlePreview(row) {
			this.previewObj = row
			this.previewVisible = true
		},
		/** 修改按钮操作 */
		handleEdit(row) {
			this.reset()
			const id = row.id || this.ids
			getMaterial(id).then((response) => {
				this.form = response.data
				this.open = true
				this.title = this.$t('material.changeMaterial')
			})
		},
		auditRecord(row) {
			const type = 'material'
			listauditRecord(type, row.id).then((response) => {
				this.title = this.$t('elButton.examineRecord')
				this.auditRecordList = response.data
				this.auditRecordOpen = true
			})
		},

		/** 素材重新上传弹窗 */
		uploadAgain(row) {
			this.uploadAgainOpen = true
			this.form = row
			this.fileList = []
		},

		/** 修改素材名称弹窗 */
		nameUpdate(id, name, groupId) {
			this.nameUpdateOpen = true
			this.form.id = id
			this.form.name = name
			this.form.groupId = groupId
		},

		/** 修改素材名称提交 */
		nameUpdateSure() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					editMaterial(this.form).then((response) => {
						if (response.code === 0) {
							this.msgSuccess(this.$t('loginLog.changeSuccess'))
							this.nameUpdateOpen = false
							this.getList()
						} else {
							this.msgError(response.msg)
						}
					})
				}
			})
		},

		/** 提交按钮 */
		submitForm: function() {
			this.$refs['form'].validate((valid) => {
				for(let key in this.formList){
					if (valid) {
						// 更新重置自动转换的值
						this.formList[key].isConvert = this.form.isConvert
						this.formList[key].groupId = this.form.groupId
						this.formList[key].groupName = getLabelByValInTree(
							this.groupOptions,
							this.formList[key].groupId,
							{
								label: 'name',
								value: 'id',
							}
						)
						if (this.formList[key].id) {
							editMaterial(this.formList[key]).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('loginLog.changeSuccess'))
									this.uploadAgainOpen = false
									this.isVideoMaterial = false
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						} else {
							addMaterial(this.formList[key]).then((response) => {
								if (response.code === 0) {
									this.msgSuccess(this.$t('addSuccess'))
									this.open = false
									this.isVideoMaterial = false
	
									this.getList()
								} else {
									this.msgError(response.msg)
								}
							})
						}
					}
				}
				// 保存成功后重置
				this.formList = []
				})
		},
		/** 删除按钮操作 */
		handleDel(row) {
			const ids = row.id || this.ids
			this.$confirm(
				this.$t('material.deleteMaterial') +
					ids +
					this.$t('equipment.deleteEquipment2'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(function() {
					return delMaterial(ids)
				})
				.then((data) => {
					this.getList()
					this.msgSuccess(this.$t('deleteSuccess'))
				})
				.catch(function(error) {})
		},
		handleMoveTo(row) {
			const ids = row.id || this.ids
			if (!ids) {
				this.msgWarning(this.$t('material.materialSortSelect'))
				return
			}
			this.groupId = undefined
			this.groupName = undefined
			this.mtOpen = true
		},
		mtCancel() {
			this.mtOpen = false
		},
		mtSubmitForm(row) {
			const ids = row.id || this.ids
			if (!this.groupId) {
				this.msgWarning(this.$t('material.materialSortInput'))
				return
			}
			this.groupName = getLabelByValInTree(this.groupOptions, this.groupId, {
				label: 'name',
				value: 'id',
			})
			moveTo(ids, this.groupId, this.groupName).then((response) => {
				if (response.code === 0) {
					this.msgSuccess(this.$t('operationSuccess'))
					this.mtOpen = false
					this.getList()
				} else {
					this.msgError(response.msg)
				}
			})
		},
		/** 导出按钮操作 */
		handleExport(row) {
			var url = process.env.VUE_APP_BASE_API + row.originalUrl // 获取图片地址
			var a = document.createElement('a') // 创建一个a节点插入的document
			const aaaaa = new MouseEvent('click') // 模拟鼠标click点击事件
			a.download = row.name + '.' + row.format // 设置a节点的download属性值
			a.href = url // 将图片的src赋值给a节点的href
			a.dispatchEvent(aaaaa)
		},

		// 添加分组
		addGroup(node, data) {
			this.groupObj = {
				name: undefined,
				type: 'material',
				parentId: data.id,
			}
			this.groupDialogVisible = true
		},
		// 编辑分组
		editGroup(node, data) {
			this.groupObj = JSON.parse(JSON.stringify(data))
			this.groupDialogVisible = true
		},
		// 删除分组
		deleteGroup(node, data) {
			whetherMaterial(data.id).then((response) => {
				if (response.data > 0) {
					this.$message({
						message: '该分组包含素材无法删除',
						type: 'warning',
						showClose: true,
					})
					return false
				}
				this.$confirm(`确认要删除分组："${data.name}"吗?`, '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(function() {
						return delGroup(data.id)
					})
					.then(() => {
						this.getGroupTree()
						this.getList()
						this.msgSuccess('删除成功')
					})
					.catch(function() {})
			})
		},
		groupDialogClosed() {
			this.groupObj = { name: undefined }
		},
		handleClickSaveGroup() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					const fun = this.groupObj.id ? editGroup : addGroup
					fun(this.groupObj)
						.then((_) => {
							this.getGroupTree()
							this.$message({
								message: this.$t('saveSuccess'),
								type: 'success',
								showClose: true,
							})
							this.groupDialogVisible = false
						})
						.catch((_) => {})
				}
			})
		},
		showImg(auditObj) {
			return auditObj.type === 'image'
		},
		showPdf(auditObj) {
			return auditObj.type === 'file'
		},
		showVideo(auditObj) {
			return auditObj.type === 'media'
		},
		changePdfPage(val) {
			// console.log(val)
			if (val === 0 && this.currentPage > 1) {
				this.currentPage--
				// console.log(this.currentPage)
			}
			if (val === 1 && this.currentPage < this.pageCount) {
				this.currentPage++
				// console.log(this.currentPage)
			}
		},

		// pdf加载时
		loadPdfHandler(e) {
			this.currentPage = 1 // 加载的时候先加载第一页
		},
	},
}
</script>

<style lang="scss" scoped>
.tree {
	overflow-x: auto;
}

.el-tree {
	min-width: 100%;
	display: inline-block;
}

.app-container {
	.custom-tree-item {
		&:after {
			content: '';
			display: block;
			clear: both;
		}

		&:hover {
			.right-btns {
				opacity: 1;
			}
		}

		font-size: 16px;
		width: 100%;

		.right-btns {
			float: right;
			color: #000;
			opacity: 0;
			transition: 0.3s all;
			user-select: none;

			.svg-icon {
				margin: 0 2px;

				&:hover {
					color: #999;
				}
			}
		}
	}

	.custom-group {
		.el-radio {
			margin: 0 0 0 10px;
		}
	}

	.custom-dialog {
		.el-select,
		.el-input-number {
			width: 100%;
		}

		/deep/ .el-upload {
			width: 100%;

			.el-upload-dragger {
				width: 100%;
			}
		}
	}
}

.img-wrapper {
	text-align: center;
	width: 100%;
}

/deep/ .el-upload-dragger {
	width: 100%;
}

/deep/ .el-upload {
	width: 100%;
}
.dialog-info {
	width: 100%;
	height: 300px;
	border: 1px solid #000;
	overflow: scroll;
	padding: 10px;
}
</style>
